package com.asiainfo.heshanghui.activity;

import android.os.Bundle;
import android.support.percent.PercentRelativeLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.heshanghui.adapter_recyclerview.HorizontalDividerItemDecoration2;
import com.asiainfo.heshanghui.adapter_recyclerview.UniversalAdapter;
import com.asiainfo.heshanghui.configs.ConstantsME;
import com.asiainfo.heshanghui.configs.EventBusTag;
import com.asiainfo.heshanghui.configs.InterfaceConfig;
import com.asiainfo.heshanghui.entity.ScanInfo;
import com.asiainfo.heshanghui.entity.StoreInfo;
import com.asiainfo.heshanghui.networkModel.HttpUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.framework.Utils.PreferencesHelper;
import com.framework.Utils.ScreenUtils;
import com.framework.Utils.ToastUtil;
import com.framework.Utils.Utils;
import com.framework.Utils.Y;
import com.framework2.base.BiuooBaseActivity;
import com.framework2.customview.TitleView;
import com.framework2.greendao.GreenDaoManager;
import com.framework2.popupwindow.InputAccessoriesPopupwindow;
import com.framework2.utils.BiuooCollectionUtil;
import com.framework2.utils.BiuooCustomProgressDialogUtils;
import com.framework2.utils.PicToastUtil;
import com.asiainfo.heshanghui.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 入库
 *
 * @author Yangjie
 *         className PutInStoreActivity
 */
public class PutInStoreActivity extends BiuooBaseActivity {


    @BindView(R.id.titleView)
    TitleView titleView;
    @BindView(R.id.serchPercentRoot)
    PercentRelativeLayout serchPercentRoot;
    @BindView(R.id.tvPhone)
    TextView tvPhone;
    @BindView(R.id.phoneLayout)
    FrameLayout phoneLayout;
    @BindView(R.id.tvAccessories)
    TextView tvAccessories;
    @BindView(R.id.accessoriesLayout)
    FrameLayout accessoriesLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tvRecord)
    TextView tvRecord;

    private UniversalAdapter adapter;
    private List<StoreInfo> storeInfoList = new ArrayList<>();
    private boolean requestSuccess;
    private int currentType = 0;
    private int page = 1;
    private int pageSize = 300;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_put_in_store);
        ButterKnife.bind(this);
        Utils.setTranslucentStatus(this, true);
        Utils.setStatusBarTintColor(this,
                getResources().getColor(R.color.white));
        initView();
        initRecyclerView();
        BiuooCustomProgressDialogUtils.showProcessDialog(PutInStoreActivity.this, "库存列表");
        requestStoreList(0);
    }

    //eventBus通知新消息
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.GOODS_TYPE)
    public void receivedNewMessage(String info) {
    }

    private void initView() {
        titleView.setTitle("商品入库").showRightMarkIcon(false).setImageDrawableRes(R.mipmap.biuoo_icon_right1);
    }

    @SuppressWarnings("unchecked")
    private void initRecyclerView() {
        //第一种，简单的颜色，高度,水平分割线
        HorizontalDividerItemDecoration2 horizontalDividerItemDecoration = new HorizontalDividerItemDecoration2(PutInStoreActivity.this);
        horizontalDividerItemDecoration.setColor(this, R.color.gray);
        horizontalDividerItemDecoration.setDividerHeightPx(1);
        recyclerView.addItemDecoration(horizontalDividerItemDecoration);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

//        if (BiuooCollectionUtil.getInstance().isEmpty(storeInfoList)) {
//
//        }
        adapter = initAdapter(adapter);
        recyclerView.setAdapter(adapter);
    }

    /**
     * @param adapter adapter
     * @return UniversalAdapter
     */
    @SuppressWarnings("unchecked")
    private UniversalAdapter initAdapter(UniversalAdapter adapter) {
        final DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
        decimalFormat.applyPattern("0.00");
        if (adapter == null) {
            adapter = new UniversalAdapter<StoreInfo>(PutInStoreActivity.this, R.layout.listitem_store, storeInfoList) {
                @Override
                protected void getItemView(UniversalViewHolder viewHolder, final StoreInfo info, int position) {
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) ((ScreenUtils.getInstance().getScreenHeightPx(PutInStoreActivity.this) - ScreenUtils.getInstance().getStatusBarHeightPx(PutInStoreActivity.this) - ScreenUtils.getInstance().dip2px(PutInStoreActivity.this, 50)) * 0.11));
                    viewHolder.itemView.setLayoutParams(params);
                    SpannableString spannableString = new SpannableString(info.getCount() + (info.getProductType() == 1 ? "台" : "件"));
                    spannableString.setSpan(new AbsoluteSizeSpan(10, true), String.valueOf(info.getCount()).length(), spannableString.length(),
                            Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    viewHolder.setText(R.id.tv_count, spannableString);
                    viewHolder.setText(R.id.tv_name, info.getName());
                    ImageView imageView = viewHolder.getView(R.id.ivIcon);
                    Glide.with(PutInStoreActivity.this).load(info.getImgUrl()).placeholder(R.mipmap.default_icon).error(R.mipmap.default_icon)
                            .priority(Priority.HIGH).into(imageView);
//                    viewHolder.setText(R.id.tv_price, "建议售价:" + decimalFormat.format(info.getPrice()) + "元");
                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (info.isPhone()) {
                                startActivity(ScanPutInStoreActivity.class, info);
                            } else {
                                showInputPop(info);
                            }
                        }
                    });
                }
            };
        }
        return adapter;
    }

    /**
     * 显示配件输入pop
     */
    private void showInputPop(final StoreInfo info) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        final InputAccessoriesPopupwindow pop = new InputAccessoriesPopupwindow(this);
        pop.setTitle(TextUtils.isEmpty(info.getName()) ? "配件名称未知" : info.getName());
        pop.setContentVisible(false);
        pop.setSureButtonText("确定");
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Utils.isCloseSoftInputMethod(PutInStoreActivity.this, pop.getEditText(), true);
            }
        });
        pop.setHintTop("请输入入库数量");
        pop.setOnSureClickListener(new InputAccessoriesPopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String info1) {
                Utils.isCloseSoftInputMethod(PutInStoreActivity.this, pop.getEditText(), true);
                try {
                    int number = Integer.parseInt(info1);

                    if (number < 1) {
                        PicToastUtil.showPicToast(PutInStoreActivity.this, "入库数量不能小于1:");
                        return;
                    }
                } catch (Exception e) {
                    PicToastUtil.showPicToast(PutInStoreActivity.this, "入库数量必须为正整数");
                    return;
                }

                ScanInfo scanInfo = new ScanInfo();
                scanInfo.setIsPhone(false);
                scanInfo.setPrice(0.00);
                scanInfo.setCount(Integer.parseInt(info1));
                scanInfo.setName(info.getName());
                scanInfo.setType(info.getType());
                scanInfo.setImgUrl(info.getImgUrl());

                if (insertIntoDB(scanInfo)) {
                    pop.dismiss();
                    startActivity(EditPutInStoreGoodsActivity.class,scanInfo);
                    finishActivity();
                } else {
                    ToastUtil.getInstance().showToast("添加配件异常!");
                }
            }
        }).showAsDropDown(titleView.getRightLayout());
    }

    private boolean insertIntoDB(final ScanInfo scanInfo) {
        if (null == scanInfo)
            return false;
        List list = GreenDaoManager.getInstance().queryEntityList(PutInStoreActivity.this, ScanInfo.class);
        if (BiuooCollectionUtil.getInstance().isEmpty(list)) {
            boolean a = GreenDaoManager.getInstance().insertEntity(PutInStoreActivity.this, scanInfo);
            Y.y("插入数据库:" + a);
            return a;
        } else {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                ScanInfo info = (ScanInfo) list.get(i);
                if (null != info && TextUtils.equals(info.getType(), scanInfo.getType()) && info.getPrice() == scanInfo.getPrice()) {
                    info.setCount(scanInfo.getCount() + info.getCount());
                    boolean b = GreenDaoManager.getInstance().updateEntity(PutInStoreActivity.this, info);
                    Y.y("更新成功：");
                    return b;
                }
            }
            boolean ins = GreenDaoManager.getInstance().insertEntity(PutInStoreActivity.this, scanInfo);
            Y.y("内部：" + ins);
            return ins;
        }
    }

    private void requestStoreList(int type) {
//        if (TextUtils.isEmpty(PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId))) {
//            ConstantRequestUtil.getInstance().requestJustShopIds(this);
//            Utils.h.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    requestStoreList_();
//                }
//            }, 100);
//        } else {
        requestStoreList_(type);
//        }
    }

    private void requestStoreList_(int type) {
        storeInfoList.clear();
        adapter.notifyDataSetChanged();
        HttpUtil.getInstance().requestStoreList(this, InterfaceConfig.storeList, PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId), type, "", page, pageSize, new HttpUtil.OnRequestListResult<StoreInfo>() {
            @Override
            public void onSuccess(List<StoreInfo> list, String... msg) {
                requestSuccess = true;
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
                    if (page == 1) {
                        storeInfoList.clear();
                    }
                    storeInfoList.addAll(list);
                    adapter.notifyDataSetChanged();
                } else if (page == 1 || BiuooCollectionUtil.getInstance().isEmpty(storeInfoList)) {
                    page = 1;
                }
                try {
                    String totalCount = msg[0];
                    int totalCount_ = Integer.parseInt(totalCount);
                } catch (Exception e) {
                }
            }

            @Override
            public void onFail(int code, String msg) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (page == 1) {
                    storeInfoList.clear();
                }
            }
        });
    }


    @OnClick({R.id.phoneLayout, R.id.accessoriesLayout, R.id.tvRecord,R.id.serchPercentRoot})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.phoneLayout:
                tvPhone.setTextColor(getResources().getColor(R.color._blue));
                tvAccessories.setTextColor(getResources().getColor(R.color._gray_dark));
                if (currentType != 0) {
                    currentType = 0;
                    requestStoreList(0);
                }
                break;
            case R.id.accessoriesLayout:
                tvPhone.setTextColor(getResources().getColor(R.color._gray_dark));
                tvAccessories.setTextColor(getResources().getColor(R.color._blue));
                if (currentType != 1) {
                    currentType = 1;
                    requestStoreList(1);
                }
                break;
            case R.id.tvRecord:
                startActivity(BiuooHomepageActivity.class);//入库记录
                break;
            case R.id.serchPercentRoot:
                startActivity(PutInStoreSearchActivity.class);//search
                break;
        }
    }

}
